<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-9-23
 * Time: 下午6:54
 */
class LoginController extends Controller{

    private $_daytime;
    private $_daydate;
    private $_now_time;


    private $_appId = "wxacd3c21e4f1582ed";
    private $_appSecret = "09ea752e7acc74e358b5d78886af7343";
    private $_redirect = "http://m.sumibuy.com/login/wxbinding/";
    private $_scope = "snsapi_userinfo";
    private $_wb_akey = "3804276570";
    private $_wb_skey = "173236157638d3da50dfec392a9f0229";


    public function init(){
        global $_wxconfig;
        $this->_session = Yaf_Session::getInstance();
        $this->_session->start();

        $this->_now_time = $_SERVER['REQUEST_TIME'];
        $__now_time = $_SERVER['REQUEST_TIME'];
        $this->_daytime = date("Y-m-d H:i:s",$__now_time);
        $this->_daydate = date("Y-m-d",$__now_time);

    }

    public function indexAction(){

        $this->_logininfo = $this->_session->offsetGet('loginInfo');

        if($this->_session->has('loginInfo')) {
            $this->redirect('/user');
            die();
        }

        //todo 下面这个很变态，我也不想的只是没有想出更好的。待后者维护吧。
        $url = empty($_SERVER["HTTP_REFERER"]) ? '/index' :$_SERVER["HTTP_REFERER"]; //获取完整的来路URL
        $str = str_replace("http://","",$url); //去掉http://
        $strdomain = explode("/",$str); // 以“/”分开成数组
        unset($strdomain[0]);
        if(empty($strdomain[1])){
            $strdomain[1] = 'index';
        }
        $back_url = implode('/',$strdomain);
        $back_url = urlencode($back_url);
        $back_url = base64_encode($back_url);

        $this->_view->title = "用户登录";
        $this->_view->back_url =$back_url;
    }

    public function loginAction(){

        if($this->_request->isPost()){

            $Post = $this->_request->getPost();

            $Post['back_url'] = !empty($Post['back_url']) ? trim($Post['back_url']) : '';
            $Post['username'] = !empty($Post['username']) ? htmlspecialchars(trim($Post['username'])) : '';
            $Post['password'] = !empty($Post['password']) ? htmlspecialchars(trim($Post['password'])) : '';
            $Post['code'] = !empty($Post['code']) ? htmlspecialchars(trim($Post['code'])) : '';
            $code = $this->_session['captcha'];


            $login = new UserModel();
            $userinfo = $login->getUserByLoginItem($Post['username']);

            $retdata = array(
                'code' => '',
                'msg'  => '',
            );
            if(strtoupper(trim($Post['code']))!=strtoupper($code)){
                $retdata = array(
                    'code' => '1004',
                    'msg'  => '非常抱歉！验证码不正确。',
                );
                echo json_encode($retdata);
                die();
            }


            if(empty($userinfo)){
                $retdata = array(
                    'code' => '1001',
                    'msg'  => '非常抱歉！该用户不存在。',
                );
                echo json_encode($retdata);
                die();
            }

            //判断用户是否冻结
            if($userinfo['is_lock'] == 'Y'){
                $retdata = array(
                    'code' => '1002',
                    'msg'  => '非常抱歉！该用户已冻结。',
                );
                echo json_encode($retdata);
                die();
            }

            //判断用户密码是否正确。
            if( $userinfo['password'] !== md5($Post['password']) ) {

                $retdata = array(
                    'code' => '1003',
                    'msg'  => '非常抱歉！该用户密码不正确。',
                );
                echo json_encode($retdata);
                die();
            }


            //开始进行返回地址处理
            if(empty($Post['back_url'])){
                //为空都返回到user
                $Post['back_url'] = base64_encode(urlencode('/user/index'));
            }else{
                $Post['back_url']= urldecode(base64_decode($Post['back_url']));
                $strdomain = explode("/",$Post['back_url']); // 以“/”分开成数组
                if($strdomain[0] == 'login'){
                    $newurl[0] = 'user';
                    $newurl[1] = 'index';
                }else{
                    $newurl = $strdomain;
                }

                $back_url = implode('/',$newurl);


            }

            if(!$this->_session->has('loginInfo')) {
                $this->_session->offsetSet('loginInfo',array());
            }
            $loginInfo = array();

            $loginInfo['id']      = $userinfo['id'];
            $loginInfo['login_name']   = $userinfo['login_name'];
            $loginInfo['realname'] = $userinfo['realname'];
            $loginInfo['moblie']  = $userinfo['moblie'];

            $this->_session->offsetSet('loginInfo',$loginInfo);

            $retdata = array(
                'code' => '1008',
                'msg'  => '登录成功！请稍等...',
                'back_url' =>  $back_url,
            );
            echo json_encode($retdata);
            die();
        }
        die();
    }

    public function logoutAction(){
        $this->_session->__unset('loginInfo');
        $this->redirect ( '/' );
        die();
    }

    //获取验证码
    public function codeAction(){
        Captcha::generate(4);
        die;
    }

    public function wxbindingAction(){
        $code = empty($_REQUEST['code']) ? 0 :$_REQUEST['code'];

        $wx = new WeiXin('', $this->_appId, $this->_appSecret, $debug = false);
        //根据CODE 获取 token
        $gettoken = $wx->oauthGetAccessToken($code);

        //根据openid和access_token查询用户信息
        $access_token = $gettoken['access_token'];
        $openid = $gettoken['openid'];
        $user_info = $wx->oauthUserInfo($access_token,$openid);

        //获取到用户数据先判断openID 是否存在，如果不存在  创建用户并存如OPENid, 如果存在用户OPENID 取用户并读出
        $appuser = new AppuserModel();
        $user = new UserModel();
        $isapp = $appuser->getRowByWhere("app_id ='{$user_info['openid']}' and source_type='W'");
        if(!empty($isapp)){
            $userinfo = $user->getListById($isapp['user_id']);
            $loginInfo['id']      = $userinfo['id'];
            $loginInfo['login_name']   = $userinfo['login_name'];
            $loginInfo['realname'] = $userinfo['realname'];
            $loginInfo['moblie']  = $userinfo['moblie'];
            $loginInfo['is_app_login']  = 'Y';
            $this->_session->offsetSet('loginInfo',$userinfo);
            unset($isapp);
            unset($userinfo);
        }else{
            $userarray =array(
                'login_name' =>  "sumi_".$this->_now_time,
                'login_item' =>'W',
                'user_source' => 'M',
                'user_type' => 'B',
                'user_level' => '1',
                'password' => md5(rand(1,8)),
                'realname' => empty($user_info['nickname']) ? "sumi_".$this->_now_time : $user_info['nickname'],
                'sex' => $user_info['sex'] == 1 ? 'M' :'W',
                'is_audit' => 'N',
                'reg_date' =>  $this->_daytime
            );

            $ret_id = $user->add($userarray);

            $appdata = array(
                'app_id' =>$user_info['openid'],
                'source_type'=> 'W',
                'user_id'=>$ret_id
            );
            $ret_APP = $appuser->add($appdata);

            $loginInfo['id']      = $ret_id;
            $loginInfo['login_name']   = $userarray['login_name'];
            $loginInfo['realname'] = $userarray['realname'];
            $loginInfo['moblie']  = '';
            $loginInfo['is_app_login']  = 'Y';

            $this->_session->offsetSet('loginInfo',$loginInfo);
            unset($appdata);
            unset($userarray);
        }
        $this->redirect("/user/index");
        die();
    }

    public function weixinAction(){
        $wx = new WeiXin('', $this->_appId, $this->_appSecret, $debug = false);
        $code = $wx->oauthGetCode(urlencode($this->_redirect), $this->_scope, 'STATE');
        $this->redirect($code);
        die();
    }

    public function stepAction(){
        $code = $this->_request->getParam("code");

        $this->_view->code = base64_decode($code);
    }

    public function qqloginAction(){
        $qc = new Qqlogin();
        $qc->qq_login();
        die();
    }

    public function qqcallbackAction(){
        global $_userLoginItemCfg, $_loginTypeCfg;

        $qc = new Qqlogin();
        $acs = $qc->qq_callback();
        $openid = $qc->get_openid();
        $qc = new Qqlogin($acs,$openid);
        $__now_time = $_SERVER['REQUEST_TIME'];
        $daydate = date("Y-m-d H:i:s",$__now_time);
        if(empty($openid)){
            echo "抱歉，腾讯服务器繁忙，请关掉窗口后重新再试，若多次出现同样的问题，请联系塑米城客服(4)";
            die();
        }
        $userinfo =array();
        $userinfo = $qc->get_user_info();


        if(!empty($userinfo['ret']) && $userinfo != 0){
            echo $userinfo['msg']."  --错误代码：".$userinfo['ret'];
        }

//    //获取用户资料
        $nickname = 'SuMiQQ';
        $userinfo['nickname'] = trim($userinfo['nickname']);
        if(!empty($userinfo['nickname'])){
            $nickname = $userinfo['nickname'];
        }
//        array(18) { ["ret"]=> int(0) ["msg"]=> string(0) "" ["is_lost"]=> int(0) ["nickname"]=> string(17) "明钰13661749943" ["gender"]=> string(3) "男" ["province"]=> string(0) "" ["city"]=> string(12) "爱尔巴桑" ["year"]=> string(4) "1982" ["figureurl"]=> string(73) "http://qzapp.qlogo.cn/qzapp/101266454/694BB2781B71F55147C57071B2D323AB/30" ["figureurl_1"]=> string(73) "http://qzapp.qlogo.cn/qzapp/101266454/694BB2781B71F55147C57071B2D323AB/50" ["figureurl_2"]=> string(74) "http://qzapp.qlogo.cn/qzapp/101266454/694BB2781B71F55147C57071B2D323AB/100" ["figureurl_qq_1"]=> string(69) "http://q.qlogo.cn/qqapp/101266454/694BB2781B71F55147C57071B2D323AB/40" ["figureurl_qq_2"]=> string(70) "http://q.qlogo.cn/qqapp/101266454/694BB2781B71F55147C57071B2D323AB/100" ["is_yellow_vip"]=> string(1) "0" ["vip"]=> string(1) "0" ["yellow_vip_level"]=> string(1) "0" ["level"]=> string(1) "0" ["is_yellow_year_vip"]=> string(1) "0" }

//    //将openid与第三方的帐号做关联
        if( empty($_SESSION['loginInfo']) ) {
            $_SESSION['loginInfo']  = array();
        }
        $appuser = new AppuserModel();
        $user = new UserModel();
        $user_id = $appuser->getRowByWhere("`app_id` = '{$openid}' AND `source_type` = '{$_userLoginItemCfg['Tencent']}'");



        if(empty($user_id)){
            //插入信息
            $userarray =array(
                'login_name' =>  "sumi_".$__now_time,
                'login_item' =>'Q',
                'user_source' => 'Q',
                'user_type' => 'B',
                'user_level' => '1',
                'password' => md5(rand(1,8)),
                'realname' => empty($userinfo['nickname']) ? "sumi_".$__now_time : $userinfo['nickname'],
                'sex' => $userinfo['gender'] == '男' ? 'M' :'W',
                'is_audit' => 'N',
                'reg_date' => $daydate
            );

            $ret_id = $user->add($userarray);
            $appdata = array(
                'app_id' =>$openid,
                'source_type'=> 'Q',
                'user_id'=>$ret_id
            );
            $ret_APP = $appuser->add($appdata);
            $loginInfo['id']      = $ret_id;
            $loginInfo['login_name']   = $userarray['login_name'];
            $loginInfo['realname'] = $userarray['realname'];
            $loginInfo['moblie']  = $userinfo['moblie'];
            $loginInfo['is_app_login']  = 'Y';
            $this->_session->offsetSet('loginInfo',$loginInfo);
            unset($appdata);
            unset($userarray);
        }else{
            $user_infos = $user->getlineByRow("id",$user_id['user_id']);

            $loginInfo['id']      = $user_infos['id'];
            $loginInfo['login_name']   = $user_infos['login_name'];
            $loginInfo['realname'] = $user_infos['realname'];
            $loginInfo['moblie']  = $user_infos['moblie'];
            $loginInfo['is_app_login']  = 'Y';
            $this->_session->offsetSet('loginInfo',$loginInfo);
        }

        $this->redirect("/user/index");
        die();
    }


    public function sinaloginAction(){

        $_GET['is_duihuan'] = empty($_GET['is_duihuan']) ? 0 : (int)$_GET['is_duihuan'];
        $obj = new Weibooauth( $this->_wb_akey, $this->_wb_skey);

        $callback = "http://m.sumibuy.com/login/sinacallback";
        $aurl = $obj->getAuthorizeURL( $callback );

        session_write_close();
        $this->redirect($aurl);
        die();
    }

    public function sinacallbackAction(){
        global $_userLoginItemCfg,$_loginTypeCfg;
        $__now_time = $_SERVER['REQUEST_TIME'];
        $daydate = date("Y-m-d H:i:s",$__now_time);

        $token = '';
        $o = new Weibooauth($this->_wb_akey, $this->_wb_skey);
        if (isset($_REQUEST['code']))
        {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] =  "http://m.sumibuy.com/login/sina_callback";
            try {
                $token = $o->getAccessToken( 'code', $keys ) ;
            } catch (OAuthException $e) {
                echo $e->getMessage();
            }
        }

        $c = new Saetclientv2( $this->_wb_akey, $this->_wb_skey, $token['access_token']);
        $uid_get = $c->get_uid();
        $uid = $uid_get['uid'];
        $sina_user = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息


        if(empty($sina_user['id']))
        {
            echo "从新浪微博获取用户信息失败.";
            die;
        }

        $nickname    = $sina_user['screen_name'];
        $app_user_id = $sina_user['id'];

        $appuser = new AppuserModel();
        $appuserinfo = $appuser->getRowByWhere("app_id = '{$app_user_id}' AND `source_type` = '{$_userLoginItemCfg['Sina']}'");

        if(empty($appuserinfo['user_id'])){
            $ip = Tools::getHttpHost();
            $userarray =array(
                'login_name' =>  "sumi_".$__now_time,
                'login_item' =>'S',
                'user_source' => 'S',
                'user_type' => 'B',
                'user_level' => '1',
                'password' => md5(rand(1,8)),
                'realname' => $nickname,
                'sex' => 'M',
                'is_audit' => 'N',
                'reg_date' => $daydate
            );
            $user = new UserModel();
            $ret_id = $user->add($userarray);
            $ret_APP = $appuser->add(array('app_id' =>$app_user_id, 'source_type'=> 'S', 'user_id'=>$ret_id));

            $_SESSION['loginInfo']['type']       =  $_loginTypeCfg['User'];
            $_SESSION['loginInfo']['id']   =  $ret_id;
            $_SESSION['loginInfo']['signature']  =  $userarray['realname'];
            $_SESSION['loginInfo']['is_audit']  =  $userarray['is_audit'];
            $_SESSION['is_app_login'] = true;
            unset($userarray);
        }else{
            $user = new UserModel();
            $user_infos = $user->getlineByRow('id',$appuserinfo['user_id']);
            $_SESSION['loginInfo']['type']       =  $_loginTypeCfg['User'];
            $_SESSION['loginInfo']['id']   =  $user_infos['id'];
            $_SESSION['loginInfo']['signature']  =  $user_infos['realname'];
            $_SESSION['loginInfo']['is_audit']  =  $user_infos['is_audit'];
            $_SESSION['is_app_login'] = true;
        }

        $this->redirect("/user/index");
        die();
    }
}
